package vip.rpai.notepad

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.db.*

class MyDatabaseOpenHelper(ctx: Context) :
    ManagedSQLiteOpenHelper(ctx, LeSS.DATABASE_NAME, null, 1) {
    companion object {
        private var instance: MyDatabaseOpenHelper? = null

        @Synchronized
        fun getInstance(ctx: Context): MyDatabaseOpenHelper {
            if (instance == null) {
                instance = MyDatabaseOpenHelper(ctx.applicationContext)
            }
            return instance!!
        }
    }

    override fun onCreate(db: SQLiteDatabase) {
        // 初始化的时候会建表，并检查是否已存在表，避免覆盖数据
        db.createTable(
            LeSS.TABLE_NAME, true,
            LeSS.TB_ID to INTEGER + PRIMARY_KEY + UNIQUE,
            LeSS.TABLE_INFO to TEXT,
            LeSS.TABLE_DATE to TEXT
        )
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        // 数据库版本更新时候删除表
        db.dropTable(LeSS.TABLE_NAME, true)
    }
}

// Access property for Context
val Context.database: MyDatabaseOpenHelper
    get() = MyDatabaseOpenHelper.getInstance(applicationContext)